//
//  XGPopoverTableView.swift
//  TodayNews
//
//  Created by monkey on 2020/2/13.
//  Copyright © 2020 itcast. All rights reserved.
//

import UIKit

// MARK: - XGPopoverTableView

class XGPopoverTableView: UITableView
{
    init(children: [XGBottomTabChild],selectedHandle: @escaping (XGBottomTabChild) -> Void)
    {
        self.children = children
        self.selectedHandle = selectedHandle
        
        super.init(frame: CGRect.zero, style: .plain)
        xg_registerCell(cellType: XGPopoverTableViewCell.self)
        rowHeight = 44
        dataSource = self
        delegate = self
        isScrollEnabled = false
        separatorStyle = .none
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    deinit {
        XGPrint("我去了")
    }
    
    /// 标题数组
    private let children: [XGBottomTabChild]
    /// 选中回调
    private let selectedHandle: (XGBottomTabChild) -> Void
}

extension XGPopoverTableView: UITableViewDataSource,UITableViewDelegate
{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
    {
        return children.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
    {
        let cell = tableView.xg_dequeueReusableCell(indexPath: indexPath) as XGPopoverTableViewCell
        cell.title = children[indexPath.row].name
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
    {
        selectedHandle(children[indexPath.row])
    }
}

// MARK: - XGPopoverTableViewCell

private class XGPopoverTableViewCell: UITableViewCell,XGRegisterReusableViewProtocol
{
    var title: String? {
        didSet {
            titleLabel.text = title
        }
    }
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?)
    {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        addSubview(titleLabel)
        titleLabel.snp.makeConstraints { (make) in
            make.center.equalToSuperview()
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    /// 标题
    private lazy var titleLabel: UILabel = UILabel(text: "测试", textColor: UIColor.darkGray, fontSize: 15, textAlignment: .left)
}
